import win32gui

class EnumWindowsHelper:
    def __init__(self):
        self.hwnds = {'main_hwnd': 0, 'board_hwnd': 0}

    #desktop_hwnd = win32gui.GetDesktopWindow()
    def __EnumWindowsCallback(self, hwnd, hwnds):
        title = win32gui.GetWindowText(hwnd)
        if title.startswith(hwnds['main_title']):
            hwnds['main_hwnd'] = hwnd
            print(title)

    #棋谱欣赏 记谱 均为独立窗口
    #下棋 直播 在主窗口之下
    #子窗口标题均为CChessboardPanel

    def __ChildCallback(self, hwnd, hwnds):
        if hwnds['board_hwnd']>0:
            return
        title = win32gui.GetWindowText(hwnd)
        # CChessboardPanel
        if title == hwnds['child_title']:
            hwnds['board_hwnd']=hwnd
            print(title)
        else:
            win32gui.EnumChildWindows(hwnd, self.__ChildCallback, hwnds)

    def EnumYeHuWindows(self, main_title, child_title):
        self.hwnds = {'main_hwnd': 0, 'board_hwnd': 0, 'main_title': main_title, 'child_title': child_title }
        win32gui.EnumWindows(self.__EnumWindowsCallback, self.hwnds)
        if self.hwnds['main_hwnd'] > 0:
            win32gui.EnumChildWindows(self.hwnds['main_hwnd'], self.__ChildCallback, self.hwnds)
            if self.hwnds['board_hwnd']>0:
                return self.hwnds
        return None
    
if __name__ == '__main__':
    helper = EnumWindowsHelper()
    hwnds=helper.EnumYeHuWindows('> [高级房', 'CChessboardPanel')
    hwnds=helper.EnumYeHuWindows('野狐围棋 > 记谱', 'CChessboardPanel')
    print(hwnds)
    